import { JwtService } from '@nestjs/jwt';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom, map } from 'rxjs';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';

@Injectable()
export class WechatService {
  constructor(
    private readonly httpService: HttpService,
    private readonly jwtService: JwtService,
  ) {}

  /* 获取小程序token */
  async genToken(js_code: string) {
    const params: any = {
      appid: 'wx053578771a4ce6ec',
      secret: process.env.WECHAT_SECRET,
      grant_type: 'authorization_code',
      js_code,
    };

    // 请求微信服务端接口 返回session_key和openid
    const res = await firstValueFrom(
      this.httpService
        .get('https://api.weixin.qq.com/sns/jscode2session', { params })
        .pipe(map((response) => response.data)),
    );

    const { openid, session_key, errcode } = res;

    // 如果微信服务端抛出错误，则将错误直接返回给前端
    if (errcode) {
      throw new HttpException({ ...res }, HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
      // 生成小程序鉴权token
      return this.jwtService.sign({ openid, session_key });
    }
  }
}
